// api/uploadApi.ts

/**
 * 文档上传与任务管理 API 封装
 * 对应后端 endpoints/uploads.py
 */

import { initializeApiConfig } from './config';
const API_BASE = initializeApiConfig(); 

// --- 类型定义 ---

export interface UploadResponse {
    message: string;
    file_name: string;
    pages_loaded: number;
    total_pages: number;
    file_hash: string;
    status: 'scheduled' | 'duplicate' | 'error';
    task_id?: string;
    existing_file?: string;
}

export interface TaskStatus {
    task_id: string;
    task_type: string;
    status: 'scheduled' | 'running' | 'success' | 'error';
    timestamp: string;
    message: string;
    result: { [key: string]: any } | null;
    initial_data: { [key: string]: any } | null;
}

export interface UpdateMetadataResponse {
    message: string;
    material_id: number;
    task_id: string;
    status: 'scheduled' | 'error';
}

export interface DeleteByMetadataRequestPayload {
    collection_name: string;
    filters: { [key: string]: any }; // ChromaDB 过滤器格式
}

export interface DocumentMetadataUpdatePayload {
    title?: string;
    summary?: string;
    keywords?: string[];
    // ... 更多元数据字段
    accessible_to?: string[]; // 权限字段，用于发布控制
}

export interface UpdateMetadataRequestPayload {
    material_id: number;
    collection_name: string;
    metadata: DocumentMetadataUpdatePayload;
}

export interface UploadFromTextRequestPayload {
    text_content: string;
    collection_name: string;
    metadata: {
        material_id: number;
        paper_cut_id: number;
        // 更多元数据
    };
}

// 辅助函数（用于非 202 响应）
interface ErrorDetail { detail: string; }
async function handleResponse<T>(response: Response): Promise<T> {
  if (!response.ok) {
    let errorDetail: ErrorDetail = { detail: '未知 API 错误' };
    try {
      errorDetail = await response.json();
    } catch (e) {
      const text = await response.text();
      errorDetail.detail = response.statusText + ': ' + text.substring(0, 100) + '...';
    }
    throw new Error(errorDetail.detail);
  }
  return response.json();
}

// -------------------------------------------------------------------
// --- API 方法定义 ---
// -------------------------------------------------------------------

/**
 * 1. 单文件上传并索引（返回 Task ID）
 * POST /api/v1/uploads/upload
 */
export const uploadSingleFile = async (file: File): Promise<UploadResponse> => {
  const formData = new FormData();
  formData.append('file', file);

  const response = await fetch(`${API_BASE}/uploads/upload`, {
    method: 'POST',
    body: formData,
  });

  return handleResponse(response); 
};

/**
 * 2. 批量文件上传并索引（返回 Task ID 列表）
 * POST /api/v1/uploads/upload-multiple
 */
export const uploadMultipleFiles = async (files: File[]): Promise<UploadResponse[]> => {
  const formData = new FormData();
  files.forEach(file => {
      formData.append('files', file); // 注意：后端是 List[UploadFile] 字段名应为 files
  });

  const response = await fetch(`${API_BASE}/uploads/upload-multiple`, {
    method: 'POST',
    body: formData,
  });

  return handleResponse(response); 
};

/**
 * 3. 异步任务状态查询
 * GET /api/v1/status/{task_id}
 */
export const getTaskStatus = async (taskId: string): Promise<TaskStatus> => {
  const response = await fetch(`${API_BASE}/uploads/status/${taskId}`);
  return handleResponse(response);
};

/**
 * 4. 异步元数据更新
 * POST /api/v1/update-metadata
 */
export const updateDocumentMetadata = async (
    payload: UpdateMetadataRequestPayload
): Promise<UpdateMetadataResponse> => {
    const response = await fetch(`${API_BASE}/uploads/update-metadata`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload),
    });
    // 注意：这个接口返回 202 状态码
    return handleResponse(response); 
};

/**
 * 5. 同步删除文档块
 * POST /api/v1/delete-by-metadata
 */
export const deleteByMetadata = async (
    payload: DeleteByMetadataRequestPayload
): Promise<{ status: string, message: string }> => {
    const response = await fetch(`${API_BASE}/uploads/delete-by-metadata`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload),
    });
    return handleResponse(response);
};

/**
 * 6. 异步从文本内容索引
 * POST /api/v1/upload-from-text
 */
export const uploadFromText = async (
    payload: UploadFromTextRequestPayload
): Promise<TaskStatus> => {
    const response = await fetch(`${API_BASE}/uploads/upload-from-text`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload),
    });
    // 注意：这个接口返回 202 状态码，返回 TaskStatus
    return handleResponse(response);
};